package com.dkm.orproject.dkmoa.action.jurisdiction;

import com.alibaba.fastjson.JSON;
import com.dkm.orproject.dkmoa.domain.OaLog;
import com.dkm.orproject.dkmoa.domain.OaPersonnel;
import com.dkm.orproject.dkmoa.domain.OaRole;
import com.dkm.orproject.dkmoa.domain.OaRolePersonnel;
import com.dkm.orproject.dkmoa.service.jurisdiction.OaRoleService;
import com.dkm.orproject.utils.jwt.login.UserLoginToken;
import com.dkm.orproject.utils.utils.IdToobtainUtils;
import com.dkm.orproject.utils.utils.Tools;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @ClassName : OaRoleAction  //类名
 * @Description : 角色Action  //描述
 * @Author : 石智诚  //作者
 * @Date: 2020-08-13 14:42  //时间
 */
@RestController
@RequestMapping("OaRoleAction")
public class OaRoleAction {

    /**
     * 回调值
     */
    int row=0;
    /**
     * 日志
     */
    OaLog log;
    /**
     * 登陆人
     */
    OaPersonnel person;

    /**
     * 回调map
     */
    Map<String,Object> map;

    /**
     * 角色服务接口
     */
    @Resource
    OaRoleService roleService;

    @Resource
    IdToobtainUtils utils;

    @Resource
    Tools tools;

    /**
     *查看所有角色
     * @param role 角色
     * @param page 页面
     * @param limit 数量
     * @param startTime 开始日期
     * @param endTime 结束日期
     * @return 角色的集合
     */
    @UserLoginToken
    @GetMapping("findAll")
    public Map<String,Object> findAll(HttpServletRequest request,OaRole role,
                                      String startTime,
                                      String endTime,Integer limit,Integer page){
        try {
            List<OaRole> all = roleService.findAll(role, page, limit, startTime, endTime);
            Long rowcount= roleService.rowcount(role, startTime, endTime);
            return Tools.maps(all,rowcount);
        } catch (Exception e) {
         addErrorLog(request,"角色查询",e);
        }
        return map;
    }


    /**
     * id查询
     * @param id 权限主键
     * @return 权限模型
     */
    @UserLoginToken
    @GetMapping("findById/{id}")
    public OaRolePersonnel findById(@PathVariable("id") Long id, HttpServletRequest request){
        try{
            OaRolePersonnel byIds = roleService.findByIds(id);
            if(ObjectUtils.isEmpty(byIds)){
                byIds=new OaRolePersonnel();
                byIds.setPersonnelId(0L);
            }
            return byIds;
        }catch (Exception e){
            addErrorLog(request,"角色id查询",e);
        }
        return null;
    }

    /**
     * 查询角色(下拉框)
     * @return id和角色名
     */
    @GetMapping("roleFindAll")
    @UserLoginToken
    public Map<String,Object> roleFindAll( HttpServletRequest request){
        rowMap(request);
        try{
            List<OaRole> all = roleService.findByAll();
            return Tools.maps(all, null);
        }catch (Exception e){
            addErrorLog(request,"角色查询(下拉框)",e);
        }
        return null;
    }

    /**
     * 更新和增加角色信息的
     * @param role 更改角色以后的信息
     * @param request 请求
     * @return 成功与否
     */
    @PostMapping("addOrUpdateRole")
    @UserLoginToken
    public Map<String, Object> addOrUpdateDepartment (OaRole role,
                                                      @RequestParam(value = "ids[]",required = false) Long[] ids,
                                                      HttpServletRequest request){
        rowMap(request);
        if(ObjectUtils.isEmpty(role)){
          return   tools.rowMap(map,0,null);
        }
        try {
            if (role.getPkRoleId()!=null &&role.getPkRoleId()>0){
                role.setUpdatedBy(person.getPersonnelName());
                row= roleService.update(role,ids);
                log.setLogTitle("角色更新");
            }else {
                role.setIsRevision("1");
                //公司id 随机生成
                role.setPkRoleId(utils.getNumberId());
                role.setCreatedBy(person.getPersonnelName());
                row=roleService.insert(role,ids);
                log.setLogTitle("角色增加");
            }
            log.setLogBody(JSON.toJSON(row).toString());
            log.setLogType("1");
            tools.rowMap(map, row, log);
        } catch (Exception e) {
            addErrorLog(request,"角色增加或者更新模块",e);
        }
        return map;
    }

    /**
     * 根据id查询的角色信息
     *
     * @param pkRoleId 角色ID
     * @param request 请求
     * @return 是否更新成功
     */
    @GetMapping("selectById/{pkRoleId}")
    @UserLoginToken
    public Map<String, Object> selectById(@PathVariable("pkRoleId") Long pkRoleId, HttpServletRequest request) {
        rowMap(request);
        try {
            OaRole role = roleService.selectBypkRoleId(pkRoleId);
            map.put("data",role);
        } catch (Exception e) {
            addErrorLog(request,"根据id查询的角色信息模块",e);
        }
        return map;
    }

    /**
     * 逻辑删除
     *
     * @param pkRoleId 角色ID
     * @param request       操作的
     * @return 操作的结果
     */
    @PutMapping("updateById/{pkRoleId}")
    @UserLoginToken
    public Map<String, Object> updateById(@PathVariable("pkRoleId") Long pkRoleId, HttpServletRequest request) {
        rowMap(request);
        try {
            row = roleService.updateById(pkRoleId,person.getPersonnelName(), String.valueOf(new Date()));
            log.setLogTitle("删除模块");
            log.setLogBody(JSON.toJSON(row).toString());
            log.setLogType("1");
            tools.rowMap(map, row, log);
        } catch (Exception e) {
            addErrorLog(request,"角色逻辑删除模块",e);
        }
        return map;
    }

    /**
     * 删除
     * @param  pkRoleId 角色Id
     * @param request       操作的
     * @return 结果
     */
    @UserLoginToken
    @DeleteMapping("deleteRole/{pkRoleId}")
    public Map<String, Object> delete(@PathVariable("pkRoleId") Long pkRoleId, HttpServletRequest request) {
        rowMap(request);
        try {
            row =roleService.delete(pkRoleId);
            log.setLogTitle("角色物理删除模块");
            log.setLogBody(JSON.toJSON(row).toString());
            log.setLogType("1");
            tools.rowMap(map, row, log);
        } catch (Exception e) {
            addErrorLog(request,"角色物理删除",e);
        }
        return map;
    }

    /**
     * 批量删除
     * @param ids 角色id的集合
     * @param request 请求
     * @return 删除的行数
     */
    @PostMapping("updateAll")
    @UserLoginToken
    public Map<String, Object> updateAll(@RequestParam(value = "ids[]",required = false) Long[] ids ,HttpServletRequest request) {
        rowMap(request);

        List<Long> idssi;
        if(ObjectUtils.isEmpty(ids)){
            return tools.rowMap(map,0,null);
        }else{
            idssi= Arrays.asList(ids);
        }
        try {
           row=roleService.updateAll(idssi,person.getPersonnelName(),String.valueOf(new Date()));
            log.setLogTitle("角色逻辑删除模块");
            log.setLogBody(JSON.toJSON(row).toString());
            log.setLogType("1");
            tools.rowMap(map, row, log);
        } catch (Exception e) {
            addErrorLog(request,"角色删除模块",e);
        }
        return map;
    }

    /**
     * 批量删除
     * @param ids 角色id的集合
     * @param request 请求
     * @return 是否删除的
     */
    @DeleteMapping("deleteAll")
    @UserLoginToken
   public Map<String, Object> deleteAll(@RequestParam(value = "ids[]", required = false) Long[] ids,HttpServletRequest request) {
        rowMap(request);
        List<Long> idss;
        if (ObjectUtils.isEmpty(ids)){
            return tools.rowMap(map,0,null);
        }else {
            idss= Arrays.asList(ids);
        }

        try {
            row =roleService.deleteAll(idss);
            log.setLogTitle("删除模块");
            log.setLogBody(JSON.toJSON(idss).toString());
            log.setLogType("1");
            tools.rowMap(map, row, log);
        } catch (Exception e) {
            addErrorLog(request,"部门删除模块",e);
        }
        return map;
    }

    private void addErrorLog(HttpServletRequest request, String title, Exception e){
        OaPersonnel personnel= (OaPersonnel) request.getSession().getAttribute("user");
        log=new OaLog();
        log.setLogType("0");
        log.setLogBody(JSON.toJSON(e.getStackTrace()).toString());
        log.setLogTitle(title);
        log.setLogIp(request.getRemoteAddr());
        if(ObjectUtils.isEmpty(personnel)){
            log.setCreatedBy(personnel.getPersonnelName());
        }
        tools.errorMap(log);
    }
    /**
     * 简化代码
     * @param request 请求
     */
    private void rowMap(HttpServletRequest request){
        //新建返回Map模型
        map=new HashMap<>(16);
        //获取登陆人信息
        person= (OaPersonnel) request.getSession().getAttribute("user");
        //新建日志
        log=new OaLog();
        //得到ip
        log.setLogIp(request.getRemoteAddr());
        //登陆人名称
        log.setCreatedBy(person.getPersonnelName());
    }
}
